package com.hy.study.practice.search;

/**
 * 插值查找
 */
public class InsertValueSearch {

    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        System.out.println(insertValueSearch(arr, 0, arr.length - 1, 9));
    }

    public static int insertValueSearch(int arr[], int left, int right, int value) {
        if (left > right || value < arr[0] || value > arr[arr.length - 1]) {
            return -1;
        }
        int mid = left + (right - left) * (value - arr[left]) / (arr[right] - arr[left]);
        int midValue = arr[mid];
        if (value > midValue) {
            //向右递归
            return insertValueSearch(arr, mid + 1, right, value);
        } else if (value < midValue) {
            //向左递归
            return insertValueSearch(arr, left, mid - 1, value);
        } else {
            //找到了
            return mid;
        }
    }
}
